package com.qingdai.filter;

import com.alibaba.fastjson2.JSON;
import com.qingdai.config.RequestConfig;
import com.qingdai.entities.CommonResult;
import com.qingdai.utils.JwtUtil;
import com.qingdai.utils.WebUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtCheckBeforeLogoutFilter extends OncePerRequestFilter {
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RequestConfig requestConfig;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //        如果是登录请求直接放行
        if (requestConfig.check(request)) {
            doFilter(request, response, filterChain);
        } else {
            CommonResult result = jwtUtil.getUserIdByJwt(request);
            if (result.getCode() == 200) {
                Integer jwtUserId = (Integer) result.getData();
                String RedisToken = (String) redisTemplate.opsForValue().get("loginToken-UserId:" + jwtUserId);
                if (RedisToken == null) {
                    String result1 = JSON.toJSONString(new CommonResult<>(400, "请重新登录"));
                    WebUtil.renderString(response, result1);
                } else {
                    doFilter(request, response, filterChain);
                }
            } else {
                String result1 = JSON.toJSONString(result);
                WebUtil.renderString(response, result1);
            }
        }
    }
}

